package com.smart.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smart.config.exception.ConfigException;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @Author xiaoqiang
 * @Version TypeConverter.java, v 0.1 2025年03月17日 17:03 xiaoqiang
 * @Description: TODO
 */
public class TypeConverter {
    private static final Map<Class<?>, Function<String, ?>> CONVERTERS = new HashMap<Class<?>, Function<String,?>>() {{
        CONVERTERS.put(String.class, s -> s);
        CONVERTERS.put(Integer.class, Integer::valueOf);
        CONVERTERS.put(int.class, Integer::parseInt);
        CONVERTERS.put(Long.class, Long::valueOf);
        CONVERTERS.put(long.class, Long::parseLong);
        CONVERTERS.put(Boolean.class, Boolean::valueOf);
        CONVERTERS.put(boolean.class, Boolean::parseBoolean);
        CONVERTERS.put(Double.class, Double::valueOf);
        CONVERTERS.put(double.class, Double::parseDouble);
        CONVERTERS.put(Float.class, Float::valueOf);
        CONVERTERS.put(float.class, Float::parseFloat);
        CONVERTERS.put(JSONObject.class, JSON::parseObject);
        CONVERTERS.put(JSONArray.class, JSON::parseArray);
    }};


    public static Object convertType(String value, Class<?> targetType) {
        if (value == null) return null;

        Function<String, ?> converter = CONVERTERS.get(targetType);
        if (converter != null) {
            return converter.apply(value);
        }

        // 处理枚举类型
        if (targetType.isEnum()) {
            return Enum.valueOf((Class<Enum>) targetType, value.toUpperCase());
        }

        // 处理自定义对象
        try {
            return JSON.parseObject(value, targetType);
        } catch (Exception e) {
            throw new ConfigException("类型转换失败: " + value + " => " + targetType.getName());
        }
    }

    public static String getValueType(Object value) {
        if (value == null) {
            return DataType.STRING.getCode();
        }
        Class<?> clazz = value.getClass();
        if (clazz == String.class) {
            return DataType.STRING.getCode();
        }
        if (Number.class.isAssignableFrom(clazz)) {
            return DataType.NUMBER.getCode();
        }
        if (clazz == Boolean.class) {
            return DataType.BOOLEAN.getCode();
        }
        if (value instanceof JSON) {
            return DataType.JSON.getCode();
        }
        return DataType.CUSTOM.getCode();
    }
}
